import { Request, Response } from 'express';
import { UserService } from '../services/user-service';
import { CreateUserRequest, UpdateUserRequest } from '../models/User';
import { TokenService } from '../services/token-service';
import { User } from '@prisma/client';

export class UserController {
  // 获取所有用户
  public static async getUsers(req: Request, res: Response): Promise<void> {
    try {
      const users = await UserService.getAllUsers();

      res.json({
        success: true,
        data: users,
      });
    } catch (error) {
      console.error('Error fetching users:', error);
      res.status(500).json({
        success: false,
        message: '获取用户列表失败',
      });
    }
  }

  // 根据ID获取用户
  public static async getUserById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const user = await UserService.getUserById(id);

      if (!user) {
        res.status(404).json({
          success: false,
          message: '用户不存在',
        });
        return;
      }

      res.json({
        success: true,
        data: user,
      });
    } catch (error) {
      console.error('Error fetching user:', error);
      res.status(500).json({
        success: false,
        message: '获取用户信息失败',
      });
    }
  }

  // 创建用户
  public static async createUser(req: Request, res: Response): Promise<void> {
    try {
      const userData: CreateUserRequest = req.body;

      // 验证必填字段
      if (!userData.name || !userData.email) {
        res.status(400).json({
          success: false,
          message: '姓名和邮箱为必填项',
        });
        return;
      }

      // 检查邮箱是否已存在
      const existingUser = await UserService.getUserByEmail(userData.email);
      if (existingUser) {
        res.status(400).json({
          success: false,
          message: '邮箱已存在',
        });
        return;
      }

      const newUser = await UserService.createUser(userData);

      res.status(201).json({
        success: true,
        message: '用户创建成功',
        data: newUser,
      });
    } catch (error) {
      console.error('Error creating user:', error);
      res.status(500).json({
        success: false,
        message: '创建用户失败',
      });
    }
  }

  // 更新用户
  public static async updateUser(req: Request, res: Response): Promise<void> {
    try {
      const userData: UpdateUserRequest = req.body;

      const updatedUser = await UserService.updateUser(userData);

      if (!updatedUser) {
        res.status(404).json({
          success: false,
          message: '用户不存在',
        });
        return;
      }

      res.json({
        success: true,
        message: '用户更新成功',
        data: updatedUser,
      });
    } catch (error) {
      console.error('Error updating user:', error);
      res.status(500).json({
        success: false,
        message: '更新用户失败',
      });
    }
  }

  // 删除用户
  public static async deleteUser(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const success = await UserService.deleteUser(id);

      if (!success) {
        res.status(404).json({
          success: false,
          message: '用户不存在',
        });
        return;
      }

      res.json({
        success: true,
        message: '用户删除成功',
      });
    } catch (error) {
      console.error('Error deleting user:', error);
      res.status(500).json({
        success: false,
        message: '删除用户失败',
      });
    }
  }

  // 重置密码
  public static async resetPassword(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      const { id } = req.params;

      if (!id) {
        res.status(400).json({
          success: false,
          message: '用户ID为必填项',
        });
        return;
      }

      // 重置密码
      await UserService.resetPassword(id);

      res.json({
        success: true,
        message: '重置密码成功',
      });
    } catch (error) {
      console.error('Error resetting password:', error);
      res.status(500).json({
        success: false,
        message: '重置密码失败',
      });
    }
  }

  // 修改密码
  public static async changePassword(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      const { oldPassword, newPassword } = req.body;

      // 从认证中间件获取用户ID
      const userId = req.user?.id;

      if (!userId) {
        res.status(401).json({
          success: false,
          message: '用户未认证',
        });
        return;
      }

      if (!oldPassword || !newPassword) {
        res.status(400).json({
          success: false,
          message: '旧密码和新密码为必填项',
        });
        return;
      }

      // 调用用户服务修改密码
      const success = await UserService.changePassword(
        userId,
        oldPassword,
        newPassword
      );

      if (!success) {
        res.status(400).json({
          success: false,
          message: '旧密码错误',
        });
        return;
      }

      res.json({
        success: true,
        message: '密码修改成功',
      });
    } catch (error) {
      console.error('Error changing password:', error);
      res.status(500).json({
        success: false,
        message: '修改密码失败',
      });
    }
  }

  // 用户登录
  public static async login(req: Request, res: Response): Promise<void> {
    try {
      const { email, password } = req.body;

      if (!email || !password) {
        res.status(400).json({
          success: false,
          message: '邮箱和密码为必填项',
        });
        return;
      }

      const user = await UserService.login(email, password);

      if (!user) {
        res.status(400).json({
          success: false,
          message: '邮箱或密码错误',
        });
        return;
      }

      // 生成Redis token
      const token = await TokenService.generateToken(user.id);

      res.json({
        success: true,
        message: '登录成功',
        data: {
          token,
          user: {
            id: user.id,
            name: user.name,
            email: user.email,
            avatar: user.avatar,
            position: user.position,
            phone: user.phone,
            status: user.status,
            gender: user.gender,
            birthday: user.birthday,
            bio: user.bio,
            role: user.role,
          },
        },
      });
    } catch (error) {
      console.error('Error during login:', error);
      res.status(500).json({
        success: false,
        message: '登录失败',
      });
    }
  }

  // 用户登出
  public static async logout(req: Request, res: Response): Promise<void> {
    try {
      const token = req.headers.authorization?.replace('Bearer ', '');

      if (token) {
        await TokenService.deleteToken(token);
      }

      res.json({
        success: true,
        message: '登出成功',
      });
    } catch (error) {
      console.error('Error during logout:', error);
      res.status(500).json({
        success: false,
        message: '登出失败',
      });
    }
  }
}
